﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
namespace HZ.Supervise.Web.Peculiar
{
    public partial class AreaCalogSelect : BasePage
    {
        string GID;//流水号
        static Dictionary<string, string> areasta;
        public AreaCalogSelect() 
        {
            this.ModuleNo = "特殊权限";
            this.PageOperateType = "维护";
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            GID = Request["GID"];
            if (!IsPostBack)
            {
                BingdJB();
                BingdChange();
            }
        }
        //绑定药品基本信息
        private void BingdJB()
        {
            HZ.Supervise.IBLL.IBLL_ProcureCatalog ipro = HZ.Supervise.BLLFactory.IBLL_ProcureCatalog();
            Model.View.ProcureCatalog procureCatalog = ipro.GetProcureCatalogByID(GID);
            txtCompany_SC.Text = procureCatalog.CompanyName_SC;
            txtCompany_TB.Text = procureCatalog.CompanyName_TB;
            txtFactor.Text = procureCatalog.Factor.ToString();
            txtGoodsName.Text = procureCatalog.GoodsName;
            txtMedicineModelName.Text = procureCatalog.MedicineModelName;
            txtOutLook.Text = procureCatalog.Outlookc;
            txtSortSource.Text = HZ.Supervise.Web.Function.FormatDrugSource(procureCatalog.SortSource);
            txtProcurePrice.Text = procureCatalog.ProcurePrice.ToString();
            ViewState["price"] = procureCatalog.ProcurePrice.ToString();
            txtProductName.Text = procureCatalog.ProductName;
            txtSort.Text = procureCatalog.SortName;
            txtUnit.Text = procureCatalog.Unit;

        }
        //绑定修改信息
        private void BingdChange()
        {
            HZ.Supervise.IBLL.IBLL_SpecialAuthority ipro = HZ.Supervise.BLLFactory.IBLL_SpecialAuthority();
            DataTable dt = ipro.GetProcureCatalogAllstate(GID, CurrentAccount.GetUser().Org.Area.AreaID);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["AreaID"].ToString().Equals("530100"))
                {
                    dt.Rows[i]["AreaName"] = "市辖区";
                }
                if (dt.Rows[i]["AreaID"].ToString().Equals("530101"))
                {
                    dt.Rows.Remove(dt.Rows[i]);
                    break;
                }
            }
            gvwAreaList.DataSource = dt;
            gvwAreaList.DataBind();
            InsertDictionary(dt);//保存数据到字典
        }

        private void InsertDictionary(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                areasta = new Dictionary<string, string>();
                foreach (DataRow dw in dt.Rows)
                {
                    areasta.Add(dw["AreaID"].ToString(), HZ.Common.HzConvert.ToString(dw["Aprice"]) + "|" + dw["DID"].ToString());
                }
            }
        }

        //保存
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();//前台一次性生成SQL 不用循环读取书库；
            for (int i = 0; i < gvwAreaList.Rows.Count; i++)
            {
                string strareaid = gvwAreaList.Rows[i].Cells[3].Text;//地区
                string strareaname = ((System.Web.UI.WebControls.Label)gvwAreaList.Rows[i].Cells[0].Controls[1]).Text;//地区名称
                string strprice = ((System.Web.UI.HtmlControls.HtmlInputText)gvwAreaList.Rows[i].Cells[1].Controls[1]).Value; //价格
                bool strchck = ((CheckBox)gvwAreaList.Rows[i].Cells[2].FindControl("cbkIsUsering")).Checked;//是否禁用 0 可用，1 禁用
                decimal price = 0;
                try
                {
                    if (!string.IsNullOrEmpty(strprice))
                    {
                        price = decimal.Parse(strprice);
                        if (price < 0)
                        {
                            throw new Exception();
                        }
                    }

                }
                catch (Exception)
                {

                    HZ.Web.WebUtil.Alert("请填写正确的价格！");
                    return;
                }

                sb.Append(Creatselect(strareaid, strareaname, strprice, strchck)); //Request.Form
            }
            if (sb.Length > 0)
            {
                HZ.Supervise.IBLL.IBLL_SpecialAuthority ipro = HZ.Supervise.BLLFactory.IBLL_SpecialAuthority();
                int ns = ipro.UpdateChangeall(sb.ToString());
                if (ns > 0)
                {
                    HZ.Web.WebUtil.Alert("修改成功！");
                    BingdChange();
                }
                else
                {
                    HZ.Web.WebUtil.Alert("修改失败！");
                }
            }
        }
        //对比字典
        private string Creatselect(string strareaid, string strareaname, string strprice, bool strchck)
        {
            StringBuilder sb = new StringBuilder();//前台一次性生成SQL 不用循环读取书库；
            string price = areasta[strareaid].Split('|')[0].ToString();//原始价格
            string check = areasta[strareaid].Split('|')[1].ToString();//原始删除状态
            string userid = CurrentAccount.GetUser().UserID;//用户ID
            if (!price.Equals(strprice))//修改价格
            {
                //给类赋值方便日志记录
                HZ.Supervise.Model.View.ViewAraepriceLoge vare = new HZ.Supervise.Model.View.ViewAraepriceLoge();
                vare.Aaddtime = System.DateTime.Now;
                vare.Aadduserid = userid;
                vare.Aprice = strprice;
                vare.oldPrice = price;
                vare.ProcureCatalogID = GID;
                vare.Areaid = strareaid;
                vare.Arearname = strareaname;
                if (price.Equals(""))//初始为空说明没改过价格，添加
                {
                    //0 医院采购范围，1地区采购药品 ，2地区采购价格
                    vare.oldPrice = txtProcurePrice.Text;//空是原价赋 省价
                    sb.Append("insert TB_AreaPrice(Areaid,ProcureCatalogID,Aprice,Aadduserid) values('" + strareaid + "','" + GID + "','" + strprice + "','" + userid + "') \n");
                    sb.Append("insert TB_AreaPriceHospitalLoge( Lareaid,Lgoodsid, Ladduserid, Lcontent,Lsort)  values('" + vare.Areaid + "','" + vare.ProcureCatalogID + "','" + vare.Aadduserid + "','" + Fun2.SoapSerializer(vare) + "','2') \n");
                }
                else//初始有值，更新
                {
                    sb.Append("update  TB_AreaPrice set Aprice='" + strprice + "' where Areaid='" + strareaid + "' and ProcureCatalogID='" + vare.ProcureCatalogID + "' \n");
                    sb.Append("insert TB_AreaPriceHospitalLoge( Lareaid,Lgoodsid, Ladduserid, Lcontent,Lsort)  values('" + vare.Areaid + "','" + vare.ProcureCatalogID + "','" + vare.Aadduserid + "','" + Fun2.SoapSerializer(vare) + "','2') \n");
                }
            }
            if (!check.Equals(strchck.ToString()))//修改删除
            {
                HZ.Supervise.Model.View.ViewAreaDeleteProcure vadp = new HZ.Supervise.Model.View.ViewAreaDeleteProcure();
                vadp.Aaddtime = System.DateTime.Now;
                vadp.Aadduserid = userid;
                vadp.Areaid = strareaid;
                vadp.Arearname = strareaname;
                vadp.ProcureCatalogID = GID;
                if (check.Equals("True"))//初始为可以用，不同则说明可用，添加
                {  //0 医院采购范围，1地区采购药品 ，2地区采购价格
                    vadp.Isdeleoradd = "禁用";
                    sb.Append("delete TB_AreaDeleteProcure where  DAreaid='" + vadp.Areaid + "' and DProcureCatalogID='" + vadp.ProcureCatalogID + "' \n");
                    //删除医院禁用药品
                    sb.Append("delete TB_HospitalGoods where HHospitalID in(select HospitalID from TB_Hospital where AreaID='" + vadp.Areaid + "') and HGoodsId='" + vadp.ProcureCatalogID + "'");
                   
                    sb.Append("insert TB_AreaDeleteProcure (DAreaid,DProcureCatalogID,Duserid) values('" + strareaid + "','" + GID + "','" + userid + "') \n");
                    //插入医院禁用药品
                    sb.Append("insert TB_HospitalGoods(HHospitalID,HGoodsId,Huserid,Hchangetime)SELECT * FROM (select HospitalID HHospitalID,'"+GID+"' HGoodsId,'"+userid+"' Huserid,GETDATE() Hchangetime from TB_Hospital where AreaID='"+strareaid+"') a where (a.HHospitalID+CAST(a.HGoodsId as varchar(max))) not in (select  HHospitalID+CAST(HGoodsId as varchar(max)) from TB_HospitalGoods) ");

                    sb.Append("insert TB_AreaPriceHospitalLoge(  Lareaid,Lgoodsid, Ladduserid, Lcontent,Lsort)  values('" + vadp.Areaid + "','" + vadp.ProcureCatalogID + "','" + vadp.Aadduserid + "','" + Fun2.SoapSerializer(vadp) + "','1') \n");
                }
                else//初始为1 说明原来就是禁用现在改为0 ，删除
                {
                    vadp.Isdeleoradd = "授权";
                    sb.Append("delete TB_AreaDeleteProcure where  DAreaid='" + vadp.Areaid + "' and DProcureCatalogID='" + vadp.ProcureCatalogID + "' \n");
                    //删除医院禁用药品
                    sb.Append("delete TB_HospitalGoods where HHospitalID in(select HospitalID from TB_Hospital where AreaID='" + vadp.Areaid + "') and HGoodsId='" + vadp.ProcureCatalogID + "'");
                    sb.Append("insert TB_AreaPriceHospitalLoge(  Lareaid,Lgoodsid, Ladduserid, Lcontent,Lsort)  values('" + vadp.Areaid + "','" + vadp.ProcureCatalogID + "','" + vadp.Aadduserid + "','" + Fun2.SoapSerializer(vadp) + "','1') \n");
                }
            }
            return sb.ToString();
        }
    }
}
